package service

import (
	"RedWork/util/errmsg"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	//"net/http"
	"time"
)

const PrivateKey = "lightos"

type JWTKey struct {
	Key []byte
}

type MyClaims struct {
	UserID   int    `json:"user_id"`
	UserName string `json:"username"`
	//Password string`json:"password"`
	jwt.StandardClaims
}

// 生成一个Token
func (j *JWTKey) CreateToken(claim MyClaims) (string, error) {
	claim.ExpiresAt = time.Now().Add(2 * time.Hour).Unix()
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	return token.SignedString(j.Key)
}

// 解析一个Token
func (j *JWTKey) ParserToken(tokenString string) (*MyClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return j.Key, nil
	})

	if token != nil {
		//Valid : Is the token valid?  Populated when you Parse/Verify a token
		if claims, ok := token.Claims.(*MyClaims); ok && token.Valid {
			return claims, nil
		}
	}
	return nil, err
}

//JWT中间件
func MiddlewareJWT() gin.HandlerFunc {
	JwtKey := JWTKey{Key: []byte(PrivateKey)}
	return func(c *gin.Context) {
		var cl *MyClaims
		var code int
		//var data interface{}
		//var uid int
		code = errmsg.SUCCSE
		token := c.Query("token")
		if token == "" { //参数没有就在post里面找
			token = c.PostForm("token")
		}
		fmt.Println(token)

		if token == "" {
			code = errmsg.ERROR_INVALID_PARAMS
		} else {
			claims, err := JwtKey.ParserToken(token)
			cl = claims
			if err != nil {
				code = errmsg.ERROR_TOKEN_WRONG
			} else if time.Now().Unix() > claims.ExpiresAt {
				code = errmsg.ERROR_TOKEN_RUNTIME
			}
		}

		if code != errmsg.SUCCSE {
			c.Set("token_code", code)
			c.Set("uid", 0)
			c.Next()
		}
		if code == errmsg.SUCCSE {

			c.Set("uid", cl.UserID)
			//c.Keys["uid"] = uid
		}
		c.Set("token_code", errmsg.SUCCSE)
		//c.Keys["token_code"] = errmsg.SUCCSE
		c.Next()
	}
}
